//
//  LocaViewController.m
//  RONGAO
//
//  Created by wei wang on 2017/3/14.
//  Copyright © 2017年 wei wang. All rights reserved.
//

#import "LocaViewController.h"
#import "PlayViewController.h"
#import "CameraTableViewCell.h"
#import "DeletView.h"
NSString * const isSelect = @"选中";
NSString * const offSelect = @"取消选中";
NSString * const photoSelect = @"photoSelect";
@interface LocaViewController ()<UITableViewDataSource,UITableViewDelegate>{
    BOOL isEditor; //编辑模式
}

/** tableview **/
@property(nonatomic,strong) UITableView *tableView;

@property (nonatomic,strong)NSMutableArray *dataSource;

/** camera **/
@property(nonatomic,strong) Camera *camera;

@property (nonatomic,strong)NSMutableArray *selectArray;

/** deletselctImageInfo **/
@property(nonatomic,strong) NSMutableArray *deletselctImageArray;

/** deleview **/
@property(nonatomic,strong) DeletView *deletView;

@end



@implementation LocaViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.camera = [AppDelegate globalDelegate].cameraModel;

    [self setNavigationStyle];
    [self masLayoutSubview];
    [self configSelectArray];
    
    __weak typeof(self) weakself = self;

    self.deletView.deletEvent = ^(){
        
        [weakself deletePhotos];
        
    };


}

- (void)setNavigationStyle{
    [self setNavigationTitle:@"本地视频" titleColor:[UIColor colorWithRed:210/255.0 green:177/255.0 blue:104/255.0 alpha:1]];
    [self setLeftButtonImage:[UIImage imageNamed:@"icon_back_nor"]];
    [self setRightButtonTitle:@"编辑"];

}

#pragma mark - tableview DataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSource.count;
    
}
#pragma mark - tableview Delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 56;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return CGFLOAT_MIN;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return CGFLOAT_MIN;
    
}



-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CameraTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSInteger row = indexPath.row;
    NSString *rootTime = self.dataSource[indexPath.row];
    NSArray *rootList = [rootTime componentsSeparatedByString:@"."];
    if (rootList.count > 0) {
        
        NSDate *datetime = [NSDate dateWithTimeIntervalSince1970:[rootList[0] integerValue]];
        
        NSLog(@"%@",datetime);
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"YYYY-MM-dd"];
        
        NSDateFormatter *formatter2 = [[NSDateFormatter alloc] init];
        [formatter2 setDateFormat:@"HH"];
        
        NSString *confromTimespStr = [formatter stringFromDate:datetime];
        NSString *endfromTimespStr = [formatter2 stringFromDate:datetime];

        NSString *time = [NSString stringWithFormat:@"MP4_%@_%@.mp4",confromTimespStr,endfromTimespStr];
        
        
        cell.title.text = time;

        if (isEditor == YES) {
            
            cell.palceView.hidden = NO;
            
            BOOL hight = [self selectImageHidenWith: [_selectArray[row] valueForKey:photoSelect]];
            if (hight==YES) {
                
                [cell.selectImage setHighlighted:NO];

            }else if (hight == NO){
                
                [cell.selectImage setHighlighted:YES];

            }
   

            
        }else if (isEditor == NO){
            
            cell.palceView.hidden = YES;
        }
        
    }

    
    return cell;
}

- (BOOL)selectImageHidenWith:(NSString *)string
{
    if ([string isEqualToString:offSelect]) {
        return YES;
    }
    return NO;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
//    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSInteger row = indexPath.row ;
    NSString *imagefile = self.dataSource[indexPath.row];

    if (isEditor) {
        
        CameraTableViewCell *cell =(CameraTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
        if (cell.palceView.hidden == NO) {
            
            BOOL hight = [self selectImageHidenWith: [_selectArray[indexPath.row] valueForKey:photoSelect]];
            
            if (hight == YES) {
                
                [self.deletselctImageArray addObject:imagefile];
                [_selectArray[row] setValue:isSelect forKey:photoSelect]; //选中


            }else{
                
                [_selectArray[row] setValue:offSelect forKey:photoSelect]; //未选中状态
                [self.deletselctImageArray removeObject:imagefile];

            }



        }
        
        
        [self.tableView reloadData];

    }else{
        
        PlayViewController *vc = [PlayViewController new];
        vc.videoPath = self.directoryPath;
        vc.videoFileName = [NSString stringWithFormat:@"%@.mp4", self.dataSource[indexPath.row]];
        
        self.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];

    }
    
    
}

- (void)masLayoutSubview{
    
    __weak UIView *superView = self.view;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(superView.mas_top);
        make.left.mas_equalTo(superView.mas_left);
        make.right.mas_equalTo(superView.mas_right);
        make.height.mas_equalTo(pxScaleHeight(1750));
    }];
    [self.deletView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.bottom.mas_equalTo(superView.mas_bottom);
        make.right.mas_equalTo(superView.mas_right);
        make.left.mas_equalTo(superView.mas_left);
        make.height.mas_equalTo(pxScaleHeight(170));
        
    }];

}


- (NSInteger)dataSourceNum:(NSString *)uid type:(NSInteger)type
{
    NSInteger num = 0;
    
    if(1 == type) {
        FMResultSet *rs = [[AppDelegate globalDelegate].database executeQuery:@"SELECT * FROM record WHERE dev_uid=?", uid];
        while([rs next]) {
            ++num;
        }
        [rs close];
    }
    //NSLog(@"uid:%@   num:%d", uid, num);
    return num;
}



- (UITableView *)tableView{
    
    if (!_tableView) {
        
        __weak UIView *superView = self.view;
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        [superView addSubview:_tableView];
        //        _tableView.separatorStyle = UITableViewCellSelectionStyleNone;//隐藏tableView的分割线
        //        _tableView.scrollEnabled = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerNib:[UINib nibWithNibName:@"CameraTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    }
    
    return _tableView;
    
}

- (NSMutableArray *)dataSource{
    
    if (!_dataSource) {
        
        
            NSMutableArray *mutableArray = [[NSMutableArray alloc] init];
            FMResultSet *rs = [[AppDelegate globalDelegate].database executeQuery:@"SELECT * FROM record WHERE dev_uid=?", self.camera.uid];
            
            while([rs next]) {
                
                NSString *filePath = [rs stringForColumn:@"file_path"];
                NSLog(@"DB-record-file_path:%@", filePath);
                [mutableArray addObject:[NSString stringWithFormat:@"%@", filePath]];
                
            }
            [rs close];
        
        NSArray *result = [mutableArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
            
            NSLog(@"%@~%@",obj1,obj2); //3~4 2~1 3~1 3~2
            
            return [obj2 compare:obj1]; //降序
            
        }];
        
        NSLog(@"result=%@",result);
        
            _dataSource = [NSMutableArray arrayWithArray:result];
        
            [self.tableView reloadData];
            
        
    }
    return _dataSource;
}

#pragma makr - store
-(void)configSelectArray
{
    _selectArray = [NSMutableArray array];
    //赋值初始状态
    
        for (int i = 0; i < self.dataSource.count; i++) {
            NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithDictionary:@{photoSelect:offSelect}];
            [_selectArray addObject:dictionary];
        }
        
    
}

#pragma mark - 点击事件

/**
 右边按钮点击
 
 @param sender sender
 */
- (void)onRightButtonClick:(UIButton *)sender
{
    [self.deletselctImageArray removeAllObjects];
    
    if ([sender.currentTitle isEqualToString:@"编辑"]){ // 进入编辑模式
        
        isEditor = YES;
        [self  setLeftButtonImage:nil];
        [self setLeftButtonTitle:@"全选"];
        [self setRightButtonTitle:@"完成"];
        [self.tableView reloadData];
        self.deletView.hidden = NO;

        return;
    }
    
    if ([sender.currentTitle isEqualToString:@"完成"]){ //退出编辑模式
        isEditor = NO;
        [self setNavigationStyle];
        self.deletView.hidden = YES;
        
        //清除所有选中
        for (int i = 0; i < _selectArray.count; i++) {
            [_selectArray[i]  setValue:offSelect forKey:photoSelect];
        }
        [self.tableView reloadData];
        return;
    }
    
}



/**
 重写父类方法 左边按钮点击事件
 
 @param sender sender
 */
- (void)onLeftButtonClick:(UIButton *)sender
{
    if (isEditor) { //编辑模式
        //点击全选
        if ([sender.currentTitle isEqualToString:@"全选"]) {
            
            for (int i = 0; i < _selectArray.count; i++) {
                [_selectArray[i]  setValue:isSelect forKey:photoSelect];
            }
            
            [self setLeftButtonTitle:@"取消"];
        
            for (int j = 0; j < self.dataSource.count; j++) {
                        
                NSString *str = self.dataSource[j];
                [self.deletselctImageArray addObject:str];
                
            }
            [self.tableView reloadData];

            return;
        }
        
        if ([sender.currentTitle isEqualToString:@"取消"]) {
            
            [self setLeftButtonTitle:@"全选"];
            
            for (int i = 0; i < _selectArray.count; i++) {
                [_selectArray[i]  setValue:offSelect forKey:photoSelect];
            }
            sender.titleLabel.text = @"全选";
            
            [self.deletselctImageArray removeAllObjects];
            
            [self.tableView reloadData];
            return;
        }
        
        
    }else{
        
        if ([self.navigationController.visibleViewController isMemberOfClass:[UITabBarController class]]) {
            return;
        }
        [self.navigationController popViewControllerAnimated:YES];
        
    }
}

/**
 重写父类方法 左边按钮
 
 @param title title
 */
- (void)setLeftButtonTitle:(NSString *)title{
    
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.leftButton];
    [self.leftButton setTitleColor:[UIColor colorWithHexString:@"#dab866"] forState:UIControlStateNormal];
    [self.leftButton.titleLabel setFont:[UIFont systemFontOfSize:14.0f]];
    [self.leftButton setTitle:title forState:UIControlStateNormal];
    [self.leftButton setFrame:CGRectMake(0, 0, BASE_TEXTSIZE(title, self.leftButton.titleLabel.font).width, BASE_TEXTSIZE(title,self.leftButton.titleLabel.font).height)];
}

- (DeletView *)deletView{
    
    if (!_deletView){
        
        _deletView = [[DeletView alloc] initWithFrame:self.view.bounds];
        _deletView.backgroundColor = [UIColor whiteColor];
        _deletView.hidden = YES;
        [self.view addSubview:_deletView];
    }
    
    return _deletView;
}


#pragma mark - --------------------------删除部分--------------------------

- (void)deletePhotos {
    NSLog(@"+++func   deletePhotos");
    
   if (self.deletselctImageArray.count > 0) {
        
        
        for (NSString *photoFile in self.deletselctImageArray) {
            
            NSLog(@"=====photoFile:%@",photoFile);
            [self deleteSnapshotRecords:photoFile];
            
            //[self deletePhotoAtIndex:[index integerValue]];
        }
        
    }else{
        
        return [SVProgressHUD showInfoWithStatus:@"请选择需要删除的视频"];
    }
   
    
}

- (NSString *) pathForDocumentsResource:(NSString *) relativePath {
    
    static NSString* documentsPath = nil;
    
    if (nil == documentsPath) {
        
        NSArray* dirs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        documentsPath = [dirs objectAtIndex:0];
    }
    
    return [documentsPath stringByAppendingPathComponent:relativePath];
}
- (void)deleteSnapshotRecords:(NSString *)fileName {
    
    if ([AppDelegate globalDelegate].database != NULL) {
        
        FMResultSet *rs = [[AppDelegate globalDelegate].database executeQuery:@"SELECT * FROM record WHERE file_path=?", fileName];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        while([rs next]) {
            
            NSString *filePath = [rs stringForColumn:@"file_path"];
            [fileManager removeItemAtPath:[self pathForDocumentsResource: [NSString stringWithFormat:@"%@.mp4", filePath]] error:NULL];
            NSLog(@"camera(%@) record removed", [NSString stringWithFormat:@"%@.mp4", filePath]);
            [fileManager removeItemAtPath:[self pathForDocumentsResource: [NSString stringWithFormat:@"%@.t.jpg", filePath]] error:NULL];
            NSLog(@"camera(%@) record removed", [NSString stringWithFormat:@"%@.t.jpg", filePath]);

        }
        
        [rs close];
        
        [[AppDelegate globalDelegate].database executeUpdate:@"DELETE FROM record WHERE file_path=?", fileName];
        
        [self.dataSource removeObject:fileName];
        isEditor = NO;
        [self setNavigationStyle];
        self.deletView.hidden = YES;
        
        //清除所有选中
        for (int i = 0; i < _selectArray.count; i++) {
            [_selectArray[i]  setValue:offSelect forKey:photoSelect];
        }
        
        [self configSelectArray];
        
        [self.tableView reloadData];

        
    }
}

- (NSMutableArray *)deletselctImageArray{
    
    if (!_deletselctImageArray) {
        
        _deletselctImageArray = [NSMutableArray array];
    }
    return _deletselctImageArray;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
